from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import json
def get_comment(url,page_num):
    web = webdriver.Firefox(executable_path='D:\\geckodriver.exe')
    web.get(url)
    for a in range(5):
        time.sleep(0.5)
        js = "var q=document.documentElement.scrollTop={}".format(1000 + a * 10000)
        web.execute_script(js)

    # 点击评论按钮
    li=web.find_element_by_css_selector('#detail > div:nth-child(1) > ul:nth-child(1) > li:nth-child(5)')
    li.click()
    # 评论
    content_list=[]
    for cc in range(int(page_num)):
        time.sleep(0.8)
        print('正在抓取第{}页评论'.format(cc+1))
        comment_list = web.find_elements_by_class_name('comment-item')
        for comment in comment_list:
            temp={}
            temp['user_name']=comment.find_element_by_class_name('user-info').text
            temp['user_img']=comment.find_element_by_class_name('user-info').find_element_by_tag_name('img').get_attribute('scr')
            temp['comment_content']=comment.find_element_by_class_name('comment-con').text
            # 这个包含了 型号 时间 等等
            temp['comment_info']=comment.find_element_by_class_name('order-info').text
            content_list.append(temp['comment_content'])
        # 翻页
        for page in web.find_element_by_class_name('ui-page').find_elements_by_tag_name('a'):
            if ('下一页' in page.text):
                page.click()

    return content_list

def temp():
    ff=open('a.txt','w',encoding='utf8')
    with open('aa.json', 'r', encoding='utf8') as file:
        data=json.load(file)
    for each in data:
        ff.write(each+'\n')
    ff.close()


if __name__ == '__main__':
    # url = 'https://item.jd.com/7293064.html'
    # mm=get_comment(url,10)
    # print(mm)
    # with open('aa.json','w',encoding='utf8') as file:
    #     json.dump(mm,file)
    # print('OK')
    temp()